/*
 * @(#)JsonStore.java
 *
 *
 *
 * ver 1.0 Sep 18, 2007 ggranum
 */
package org.testfire.realm.view.extjs.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class JsonStore implements Store
{
    /* The name of this store*/
    private final String name;

    private final String jsStoreName;

    /* The url that the json request will hit. */
    private String url = "../json/jsonRequest.jsf";
    /* The data root object, of the response. Contains an array of results. */
    private String root = "result";

    private Map<String, String > baseParams = new HashMap<String, String>();

    private List<StoreField> fields = new ArrayList<StoreField>();



    public JsonStore(String name, String jsStoreName)
    {
        this.name = name;
        this.jsStoreName = jsStoreName;
    }

    public void addField(StoreField field){
        this.fields.add( field );
    }

    public List<StoreField> getFields()
    {
        return fields;
    }

    public String getName()
    {
        return name;
    }

    public String getRoot()
    {
        return root;
    }

    public String getUrl()
    {
        return url;
    }

    public String toJavaScriptString(){
        StringBuilder b = new StringBuilder();
        b.append("var fields = " ).append( StoreField.toJsonString( this.fields )).append( ";\n") ;
        b.append( jsStoreName ).append( "." ).append( name ).append( " = new Ext.data.JsonStore( { \n" );
        b.append( "\turl: '").append( url ).append( "',\n" );
        b.append( "\troot: '").append( root ).append( "',\n" );

        if(this.baseParams.size() > 0){
            b.append( "\tbaseParams: {\n" );
            for(String key : baseParams.keySet()){
                b.append("\t\t").append( key ).append( ": '" ).append( baseParams.get( key ) ).append( "',\n" );
            }
            b.replace( b.length() - 2, b.length(), "\n\t}\n");
        }
        b.append( "\tfields: ").append( fields ).append( "\n" );
        b.append( "});");
        return b.toString();
    }

}

// eof: JsonStore.java